from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_devices_widget import Ui_widget_devices
from app.window.msg_box import Msg_box
from app.window.device_editor_dialog import Device_editor_dialog
from app.window.private_script_manager_dialog import Private_script_manager_dialog
from app.window.device_new_dialog import Device_new_dialog
import time
from database.db import Database
from app.window.custom_ui.opt_widget import Opt_widget

class devices_signal(QObject):

    # 显示设备编辑器
    show_device_editor = Signal(int) # 发送设备id

    #执行脚本
    set_tab = Signal(str) #发送页面名称给main_window 切换页面
    exec_script = Signal(int) #发送设备id到单次执行页面
     
class Devices_widget(QWidget):
    
    def __init__(self, parent=None):
        super(Devices_widget, self).__init__(parent)
        self.ui = Ui_widget_devices()
        self.ui.setupUi(self)

        self.col_names  = {}

        self.device_editor = Device_editor_dialog()
        self.device_editor.hide()
        
        self.private_script_manager = Private_script_manager_dialog()
        self.private_script_manager.hide()

        self.dialog_device_new = Device_new_dialog()

        self.signal = devices_signal()
        self.msg_box = Msg_box(self)

        # self.init_ui_feature()

        self.init_col_names()
        self.reg_hot_key()
        self.init_show_columns()
        self.init_signal_slot()


    def reg_hot_key(self):
        short = QShortcut(QKeySequence('Ctrl+F'), self)
        short.activated.connect(self.ui.pushButton_search.click)
        short = QShortcut(QKeySequence('Ctrl+Q'), self)
        short.activated.connect(self.ui.pushButton_new.click)
        short = QShortcut(QKeySequence('Alt+Z'), self)
        short.activated.connect(self.ui.tableWidget.resizeColumnsToContents)
        short = QShortcut(QKeySequence('Alt+X'), self)
        short.activated.connect(self.ui.tableWidget.resizeRowsToContents)

    def init_show_columns(self):
        self.ui.checkBox_id.stateChanged.connect(self.show_column_id)
        self.ui.checkBox_device_name.stateChanged.connect(self.show_column_device_name)
        self.ui.checkBox_supplier.stateChanged.connect(self.show_column_supplier)
        self.ui.checkBox_model.stateChanged.connect(self.show_column_model)
        self.ui.checkBox_position.stateChanged.connect(self.show_column_position)
        self.ui.checkBox_ip.stateChanged.connect(self.show_column_ip)
        self.ui.checkBox_port.stateChanged.connect(self.show_column_port)
        self.ui.checkBox_user.stateChanged.connect(self.show_column_user)
        self.ui.checkBox_password.stateChanged.connect(self.show_column_password)
        self.ui.checkBox_status.stateChanged.connect(self.show_column_status)
        self.ui.checkBox_created_time.stateChanged.connect(self.show_column_created_time)
        self.ui.checkBox_execu_time.stateChanged.connect(self.show_column_execu_time)
        self.ui.checkBox_opt.stateChanged.connect(self.show_column_opt)
        self.ui.checkBox_info.stateChanged.connect(self.show_column_info)

        
        self.ui.checkBox_id.setCheckState(Qt.Unchecked)
        self.ui.checkBox_device_name.setCheckState(Qt.Checked)
        self.ui.checkBox_supplier.setCheckState(Qt.Unchecked)
        self.ui.checkBox_model.setCheckState(Qt.Unchecked)
        self.ui.checkBox_position.setCheckState(Qt.Unchecked)
        self.ui.checkBox_ip.setCheckState(Qt.Checked)
        self.ui.checkBox_port.setCheckState(Qt.Unchecked)
        self.ui.checkBox_user.setCheckState(Qt.Unchecked)
        self.ui.checkBox_password.setCheckState(Qt.Unchecked)
        self.ui.checkBox_status.setCheckState(Qt.Checked)
        self.ui.checkBox_created_time.setCheckState(Qt.Unchecked)
        self.ui.checkBox_execu_time.setCheckState(Qt.Unchecked)
        self.ui.checkBox_opt.setCheckState(Qt.Checked)
        self.ui.checkBox_info.setCheckState(Qt.Checked)

        self.show_column_id(Qt.Unchecked)
        self.show_column_device_name(Qt.Checked)
        self.show_column_supplier(Qt.Unchecked)
        self.show_column_model(Qt.Unchecked)
        self.show_column_position(Qt.Unchecked)
        self.show_column_ip(Qt.Checked)
        self.show_column_port(Qt.Unchecked)
        self.show_column_user(Qt.Unchecked)
        self.show_column_password(Qt.Unchecked)
        self.show_column_status(Qt.Checked)
        self.show_column_created_time(Qt.Unchecked)
        self.show_column_execu_time(Qt.Unchecked)
        self.show_column_info(Qt.Checked)

    def show_column_id(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['id'],hide)
    def show_column_device_name(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['设备名'],hide)
    def show_column_supplier(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['厂商'],hide)
    def show_column_model(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['型号'],hide)
    def show_column_position(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['位置'],hide)
    def show_column_ip(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['ip'],hide)
    def show_column_port(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['端口'],hide)
    def show_column_user(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['用户'],hide)
    def show_column_password(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['密码'],hide)
    def show_column_status(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['状态'],hide)
    def show_column_created_time(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['创建时间'],hide)
    def show_column_execu_time(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['执行时间'],hide)
    def show_column_opt(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['操作'],hide)
    def show_column_info(self,check_status:int):
        if check_status == Qt.Checked:hide = False
        else:hide = True
        self.ui.tableWidget.setColumnHidden(self.col_names['描述'],hide)
  
    def init_ui_feature(self):
        self.ui.tableWidget.verticalHeader().setVisible(False)  #隐藏表头

    def init_col_names(self):
        # 获取列id
        max_col = self.ui.tableWidget.columnCount()
        for i in range(max_col):
            text = self.ui.tableWidget.horizontalHeaderItem(i).text()
            self.col_names[text] = i


    def init_signal_slot(self):
        # 按钮
        self.ui.pushButton_auto_size.clicked.connect(self.auto_tab_size)
        self.ui.pushButton_new.clicked.connect(self.dialog_device_new.slot_show)

        # 设备表
        self.signal.show_device_editor.connect(self.device_editor.slot_show)
        
        self.device_editor.signal.save_to_manger.connect(self.slot_update_row_data)

        self.dialog_device_new.signal.device_widget_new_row.connect(self.slot_new_device_row)

  
 
    def new_blank_row(self):
        row_count = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(row_count)

        for i in range(self.ui.tableWidget.columnCount()):
            item = QTableWidgetItem('')
            self.ui.tableWidget.setItem(row_count , i, item)
            self.ui.tableWidget.item(row_count ,i).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

            if i == self.col_names['描述']:
                item.setTextAlignment(Qt.AlignLeft | Qt.AlignTop)


    def init_data(self):

        db = Database()
        fields = ['id','name','supplier','model','position','ip','port','user','password','info']
        device_list = db.select('devices',fields)
        index = 0
        device_table = []
        if device_list is not None:
            for device in device_list:
                device_table.append({})
                device_table[index]['id'] = device[0]
                device_table[index]['name'] = device[1]
                device_table[index]['supplier'] = device[2]
                device_table[index]['model'] = device[3]
                device_table[index]['position'] = device[4]
                device_table[index]['ip']   = device[5]
                device_table[index]['port'] = device[6]
                device_table[index]['user'] = device[7]
                device_table[index]['password'] = device[8]
                device_table[index]['info'] = device[9]
                index += 1
        
        db.close_conn()
        self.update_device_table(device_table)

        self.auto_tab_size()

    def auto_tab_size(self):
        self.ui.tableWidget.resizeColumnsToContents() #自动列宽
        self.ui.tableWidget.resizeRowsToContents() #自动行高
        # 最后一行自动填充
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(self.ui.tableWidget.columnCount()-1,QHeaderView.Stretch)

    def update_device_table(self,data:list[dict]):
        max_row = 1
        if data is not None:
            max_row = len(data) # 需要表格行数

        rows =  self.ui.tableWidget.rowCount() # 当前表格可用行数
        k = max_row - rows
        if k >= 0: # 表格行数不够
            for i in range(k):
                self.new_blank_row()
        else:
            for i in range(rows,max_row - 1,-1):
                self.ui.tableWidget.removeRow(i)
        
        # 写入数据
        for k,v in enumerate(data):
            self.ui.tableWidget.item(k,self.col_names['id']).setText(str(v['id'])) 
            self.ui.tableWidget.item(k,self.col_names['设备名']).setText(v['name']) 
            self.ui.tableWidget.item(k,self.col_names['厂商']).setText(v['supplier']) 
            self.ui.tableWidget.item(k,self.col_names['型号']).setText(v['model']) 
            self.ui.tableWidget.item(k,self.col_names['位置']).setText(v['position']) 
            self.ui.tableWidget.item(k,self.col_names['ip']).setText(v['ip']) 
            self.ui.tableWidget.item(k,self.col_names['端口']).setText(v['port']) 
            self.ui.tableWidget.item(k,self.col_names['用户']).setText(v['user']) 
            self.ui.tableWidget.item(k,self.col_names['密码']).setText(v['password']) 
            self.ui.tableWidget.item(k,self.col_names['描述']).setText(v['info']) 
        
            wid = self.create_opt_widget(v['id'])
            
            self.ui.tableWidget.setCellWidget(k, self.col_names['操作'], wid)


      

    def create_opt_widget(self,device_id) -> Opt_widget:
        wid = Opt_widget()

        btn_edit = wid.new_btn('编辑')
        btn_script = wid.new_btn('脚本')
        btn_del = wid.new_btn('删除')
        btn_exec = wid.new_btn('执行')
        btn_edit.clicked.connect(lambda:self.device_editor.slot_show(device_id))
        btn_script.clicked.connect(lambda:self.private_script_manager.slot_show(device_id))
        btn_del.clicked.connect(lambda:self.slot_delete_device(device_id))
        # main_window中接收切换页面 execute_widget(单次执行) 接收 刷新数据
        # 先切换 再发送设备id
        btn_exec.clicked.connect(lambda:self.signal.set_tab.emit('单次执行'))
        btn_exec.clicked.connect(lambda:self.signal.exec_script.emit(device_id))
        return wid
    

   
    def slot_delete_device(self,device_id:int):
        if not self.msg_box.msg_is_ok_cancel('确认删除设备'):
            return
        
        db = Database()
        # 判断计划任务是否存在外键引用
        task_list = db.select('tasks',['id','name'],f'device_id={device_id}')
        if len(task_list) > 0:
            self.msg_box.msg_tips('计划任务中存在引用.删除对应计划任务后,再尝试')
            for data in task_list:
                print(data[0],data[1])
            db.close_conn()
            return
        # 删除设备对应的私有脚本
        script_list = db.select('private_script_device',['id','script_id'],f'device_id={device_id}')
        for data in script_list:
            db.delete('private_script_device',f'id={data[0]}') #删除对应关系
            db.delete('scripts',f'id={data[1]}')    # 删除脚本
        # 删除设备
        db.delete('devices',f'id={device_id}')
        db.close_conn()

        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == str(device_id):
                self.ui.tableWidget.removeRow(i)
                break
        
        


    # 设备编辑器保存槽函数
    def slot_update_row_data(self,data:dict):
        id = str(data['id'])
        row = -1
        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == id:
                row = i
                break
        
        if row == -1: return

        self.ui.tableWidget.item(row,self.col_names['设备名']).setText(data['name'])
        self.ui.tableWidget.item(row,self.col_names['ip']).setText(data['ip'])
        self.ui.tableWidget.item(row,self.col_names['端口']).setText(data['port'])
        self.ui.tableWidget.item(row,self.col_names['用户']).setText(data['user'])
        self.ui.tableWidget.item(row,self.col_names['密码']).setText(data['password'])
        self.ui.tableWidget.item(row,self.col_names['位置']).setText(data['position'])
        self.ui.tableWidget.item(row,self.col_names['厂商']).setText(data['supplier'])
        self.ui.tableWidget.item(row,self.col_names['型号']).setText(data['model'])
        self.ui.tableWidget.item(row,self.col_names['描述']).setText(data['info'])



    def slot_show_script_manager(self,row_index:int):
        device_id = self.ui.tableWidget.item(row_index,self.col_names['id']).text()
        self.private_script_manager.slot_show(device_id)


    def slot_show_device_editor(self,row_index:int):
        data = {
            'id':self.ui.tableWidget.item(row_index,self.col_names['id']).text(),
            'name'  :self.ui.tableWidget.item(row_index,self.col_names['设备名']).text(),
            'ip'    :self.ui.tableWidget.item(row_index,self.col_names['ip']).text(),
            'port'  :self.ui.tableWidget.item(row_index,self.col_names['端口']).text(),
            'user'  :self.ui.tableWidget.item(row_index,self.col_names['用户']).text(),
            'password':self.ui.tableWidget.item(row_index,self.col_names['密码']).text(),
            'position':self.ui.tableWidget.item(row_index,self.col_names['位置']).text(),
            'supplier':self.ui.tableWidget.item(row_index,self.col_names['厂商']).text(),
            'model' :self.ui.tableWidget.item(row_index,self.col_names['型号']).text(),
            'info':self.ui.tableWidget.item(row_index,self.col_names['描述']).text(),
        }
        self.signal.show_device_editor.emit(data)

    
    def slot_new_device_row(self,data):
        max_row = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(max_row)
        for i in range(0,self.ui.tableWidget.columnCount()):
            self.ui.tableWidget.setItem(max_row,i,QTableWidgetItem())

        self.ui.tableWidget.item(max_row,self.col_names['id']).setText(str(data['id'])) 
        self.ui.tableWidget.item(max_row,self.col_names['设备名']).setText(data['name']) 
        self.ui.tableWidget.item(max_row,self.col_names['厂商']).setText(data['supplier']) 
        self.ui.tableWidget.item(max_row,self.col_names['型号']).setText(data['model']) 
        self.ui.tableWidget.item(max_row,self.col_names['位置']).setText(data['position']) 
        self.ui.tableWidget.item(max_row,self.col_names['ip']).setText(data['ip']) 
        self.ui.tableWidget.item(max_row,self.col_names['端口']).setText(str(data['port'])) 
        self.ui.tableWidget.item(max_row,self.col_names['用户']).setText(data['user']) 
        self.ui.tableWidget.item(max_row,self.col_names['密码']).setText(data['password']) 
        self.ui.tableWidget.item(max_row,self.col_names['描述']).setText(data['info']) 
        

        wid = self.create_opt_widget()
 
        self.ui.tableWidget.setCellWidget(max_row, self.col_names['操作'], wid)